#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
语言与扩展名映射工具

集中维护项目中支持的语言及其文件扩展名映射，避免各模块重复定义。
"""

from pathlib import Path
from typing import Dict, Iterable, List, Optional, Set, Tuple, Union

# 定义基础映射（保持插入顺序以维持默认语言顺序）
_EXTENSION_LANGUAGE_ITEMS: Tuple[Tuple[str, str], ...] = (
    ('.swift', 'swift'),
    ('.m', 'objc'),
    ('.mm', 'objc'),
    ('.h', 'objc'),
    ('.java', 'java'),
    ('.kt', 'kotlin'),
    ('.kts', 'kotlin'),
)

EXTENSION_LANGUAGE_MAP: Dict[str, str] = {
    ext: language for ext, language in _EXTENSION_LANGUAGE_ITEMS
}

# 构建语言 -> 扩展名映射（使用集合避免重复，再转换为按插入顺序排序的列表）
_language_extension_sets: Dict[str, Set[str]] = {}
for ext, language in _EXTENSION_LANGUAGE_ITEMS:
    _language_extension_sets.setdefault(language, set()).add(ext)

LANGUAGE_ALIASES: Dict[str, str] = {
    'objective-c': 'objc',
    'obj-c': 'objc',
    'objectivec': 'objc',
}

LANGUAGE_EXTENSION_MAP: Dict[str, Tuple[str, ...]] = {
    language: tuple(sorted(exts))
    for language, exts in _language_extension_sets.items()
}

_language_order: List[str] = []
for _, language in _EXTENSION_LANGUAGE_ITEMS:
    canonical = LANGUAGE_ALIASES.get(language, language)
    if canonical and canonical not in _language_order:
        _language_order.append(canonical)

SUPPORTED_LANGUAGES: Tuple[str, ...] = tuple(_language_order)
SUPPORTED_EXTENSIONS: Tuple[str, ...] = tuple(ext for ext, _ in _EXTENSION_LANGUAGE_ITEMS)

EXTRA_EXTENSION_GROUPS: Dict[str, Tuple[str, ...]] = {
    'c': ('.c', '.h'),
    'cpp': ('.cpp', '.cc', '.cxx', '.hpp', '.hh', '.hxx'),
    'xml_like': ('.xml', '.storyboard', '.xib'),
    'ios_resource_text': ('.xml', '.storyboard', '.xib', '.plist', '.json', '.strings'),
}


def normalize_extension(ext: str) -> str:
    """规范化扩展名（转小写并确保包含前导点）"""
    ext = ext.lower()
    if not ext.startswith('.'):
        ext = f'.{ext}'
    return ext


def extension_to_language(ext: str) -> Optional[str]:
    """根据扩展名获取语言标识"""
    language = EXTENSION_LANGUAGE_MAP.get(normalize_extension(ext))
    if language:
        return LANGUAGE_ALIASES.get(language, language)
    return None


def canonical_language(language: str) -> str:
    """将语言名称规范化为内部标识"""
    return LANGUAGE_ALIASES.get(language.lower(), language.lower())


def language_to_extensions(language: str) -> List[str]:
    """根据语言获取支持的扩展名列表"""
    canonical = canonical_language(language)
    return list(LANGUAGE_EXTENSION_MAP.get(canonical, ()))


def detect_language_for_file(path: str) -> Optional[str]:
    """根据文件路径检测语言"""
    return extension_to_language(Path(path).suffix)


def collect_extensions(languages: Union[Iterable[str], str], *additional_languages: str) -> Set[str]:
    """为一组语言收集扩展名集合"""
    extensions: Set[str] = set()
    if isinstance(languages, str):
        languages_iter = [languages]
    else:
        languages_iter = list(languages)
    languages_iter.extend(additional_languages)
    for language in languages_iter:
        extensions.update(language_to_extensions(language))
    return extensions


def get_extension_group(group_name: str) -> List[str]:
    """获取扩展名分组"""
    return list(EXTRA_EXTENSION_GROUPS.get(group_name, ()))


__all__ = [
    'EXTENSION_LANGUAGE_MAP',
    'LANGUAGE_EXTENSION_MAP',
    'LANGUAGE_ALIASES',
    'SUPPORTED_LANGUAGES',
    'SUPPORTED_EXTENSIONS',
    'extension_to_language',
    'canonical_language',
    'language_to_extensions',
    'detect_language_for_file',
    'collect_extensions',
    'normalize_extension',
    'EXTRA_EXTENSION_GROUPS',
    'get_extension_group',
]
